use rust_utils::string_utils::*;
use rust_utils::math_utils::*;
use rust_utils::file_utils;
use rust_utils::time_utils::*;
use rust_utils::collection_utils::*;
use rust_utils::crypto_utils::*;
use rust_utils::network_utils::*;
use rust_utils::system_utils;
use rust_utils::data_structure::*;
use rust_utils::concurrent_utils::*;
use rust_utils::serialization::*;
use rust_utils::validation::*;
use rust_utils::logging::*;
use rust_utils::id_card::IdCardValidator; // 添加身份证验证模块导入
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::thread;
use std::time::Duration;

#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Person {
    id: u32,
    name: String,
    email: String,
    age: u32,
}

#[derive(Serialize, Deserialize, Debug)]
struct User {
    id: u32,
    name: String,
    email: String,
    age: u32,
}

fn demonstrate_string_utils() {
    println!("=== 字符串工具演示 ===");
    let text = "A man a plan a canal Panama";
    println!("   '{}' 是回文: {}", text, is_palindrome(text));
    println!("   '{}' 反转后: {}", text, reverse_string(text));
    println!("   '{}' 中 'a' 的个数: {}\n", text, count_char(text, 'a'));
}

fn demonstrate_math_utils() {
    println!("=== 数学工具演示 ===");
    let a = 48u64;
    let b = 18u64;
    println!("   gcd({}, {}) = {}", a, b, gcd(a, b));
    println!("   lcm({}, {}) = {}", a, b, lcm(a, b));
    let n = 17u64;
    println!("   {} 是质数: {}", n, is_prime(n));
    let f = 5u64;
    println!("   {}! = {}\n", f, factorial(f));
}

fn demonstrate_file_utils() {
    println!("=== 文件工具演示 ===");
    
    let test_file = "demo_test_file.txt";
    let content = "Hello, Rust file utils!";
    
    // 写入文件
    match file_utils::write_string_to_file(test_file, content) {
        Ok(_) => println!("   成功写入文件: {}", test_file),
        Err(e) => println!("   写入文件失败: {}", e),
    }
    
    // 读取文件
    match file_utils::read_file_to_string(test_file) {
        Ok(read_content) => println!("   读取文件内容: {}", read_content),
        Err(e) => println!("   读取文件失败: {}", e),
    }
    
    // 检查文件是否存在
    println!("   文件 {} 存在: {}", test_file, file_utils::file_exists(test_file));
    
    // 获取文件大小
    match file_utils::get_file_size(test_file) {
        Ok(size) => println!("   文件大小: {} 字节", size),
        Err(e) => println!("   获取文件大小失败: {}", e),
    }
    
    // 清理测试文件
    let _ = std::fs::remove_file(test_file);
    println!("   已清理测试文件: {}\n", test_file);
}

fn demonstrate_time_utils() {
    println!("=== 时间工具演示 ===");
    println!("   当前时间戳: {}", current_timestamp());
    println!("   当前时间戳(毫秒): {}", current_timestamp_millis());
    
    // 时间解析和格式化示例
    match parse_time("2023-01-01 12:00:00", "%Y-%m-%d %H:%M:%S") {
        Ok(dt) => {
            println!("   解析时间: {}", dt);
            println!("   格式化时间: {}", format_time(&dt, "%Y年%m月%d日 %H:%M:%S"));
            
            // 时间计算
            let future_dt = add_days(&dt, 7);
            println!("   7天后: {}", future_dt);
            
            let days_diff = days_between(&dt, &future_dt);
            println!("   时间差: {} 天", days_diff);
        },
        Err(e) => println!("   时间解析失败: {}", e),
    }
    println!();
}

fn demonstrate_collection_utils() {
    println!("=== 集合工具演示 ===");
    let set1: HashSet<i32> = [1, 2, 3, 4, 5].iter().cloned().collect();
    let set2: HashSet<i32> = [4, 5, 6, 7, 8].iter().cloned().collect();
    println!("   集合1: {:?}", set1);
    println!("   集合2: {:?}", set2);
    println!("   交集: {:?}", intersection(&set1, &set2));
    println!("   并集: {:?}", union(&set1, &set2));
    println!("   差集: {:?}", difference(&set1, &set2));

    let mut map1 = HashMap::new();
    map1.insert("a", 1);
    map1.insert("b", 2);
    let mut map2 = HashMap::new();
    map2.insert("b", 3);
    map2.insert("c", 4);
    println!("   合并HashMap: {:?}", merge_hashmap(&map1, &map2));
    
    let vec = vec![1, 2, 2, 3, 3, 3, 4];
    println!("   查找重复元素: {:?}", find_duplicates(&vec));
    println!();
}

fn demonstrate_crypto_utils() {
    println!("=== 加密/哈希工具演示 ===");
    let data = "Hello, World!";
    println!("   '{}' 的 SHA256: {}", data, sha256(data));
    println!("   '{}' 的 SHA3-256: {}", data, sha3_256(data));
    println!("   '{}' 的 MD5: {}", data, md5_hash(data));
    println!("   生成UUID: {}", generate_uuid());
    println!("   生成10位随机字符串: {}", random_string(10));
    println!("   生成1-100之间的随机数: {}\n", random_number(1, 100));
}

fn demonstrate_network_utils() {
    println!("=== 网络工具演示 ===");
    println!("   '192.168.1.1' 是有效IPv4地址: {}", is_valid_ipv4("192.168.1.1"));
    println!("   '8080' 是有效端口: {}", is_valid_port(8080));
    println!("   URL编码 'hello world': {}", url_encode("hello world"));
    match url_decode("hello%20world") {
        Ok(decoded) => println!("   URL解码 'hello%20world': {}", decoded),
        Err(e) => println!("   URL解码失败: {}", e),
    }
    println!();
}

fn demonstrate_system_utils() {
    println!("=== 系统信息工具演示 ===");
    
    // 环境变量操作
    match system_utils::get_env_var("PATH") {
        Some(path) => println!("   PATH环境变量存在 (长度: {})", path.len()),
        None => println!("   无法获取PATH环境变量"),
    }
    
    system_utils::set_env_var("DEMO_VAR", "demo_value");
    match system_utils::get_env_var("DEMO_VAR") {
        Some(value) => println!("   DEMO_VAR环境变量值: {}", value),
        None => println!("   无法获取DEMO_VAR环境变量"),
    }
    
    // 当前目录
    match system_utils::current_dir() {
        Ok(dir) => println!("   当前工作目录: {}", dir),
        Err(e) => println!("   获取当前目录失败: {}", e),
    }
    
    // 系统信息
    let sys_info = system_utils::get_system_info();
    println!("   操作系统: {}", sys_info.os_type);
    println!("   架构: {}", sys_info.arch);
    
    // 文件操作演示
    let test_file = "sys_utils_demo.txt";
    let content = "Hello from system utils!";
    
    match system_utils::write_file(test_file, content) {
        Ok(_) => println!("   成功写入系统工具测试文件"),
        Err(e) => println!("   写入系统工具测试文件失败: {}", e),
    }
    
    println!("   文件 {} 存在: {}", test_file, system_utils::file_exists(test_file));
    
    match system_utils::get_file_size(test_file) {
        Ok(size) => println!("   文件大小: {} 字节", size),
        Err(e) => println!("   获取文件大小失败: {}", e),
    }
    
    match system_utils::read_file(test_file) {
        Ok(content) => println!("   读取文件内容: {}", content),
        Err(e) => println!("   读取文件失败: {}", e),
    }
    
    // 清理测试文件
    let _ = std::fs::remove_file(test_file);
    println!("   已清理测试文件: {}\n", test_file);
}

fn demonstrate_data_structures() {
    println!("=== 数据结构演示 ===");
    
    // 演示循环缓冲区
    let mut buffer = CircularBuffer::new(3);
    buffer.push(1);
    buffer.push(2);
    buffer.push(3);
    buffer.push(4); // 这会移除最旧的元素 1
    
    println!("   循环缓冲区内容: {:?}", buffer.to_vec());
    println!("   缓冲区前端元素: {:?}", buffer.front());
    println!("   缓冲区后端元素: {:?}", buffer.back());
    
    // 演示LRU缓存
    let mut cache = LRUCache::new(3);
    cache.put("key1".to_string(), "value1".to_string());
    cache.put("key2".to_string(), "value2".to_string());
    cache.put("key3".to_string(), "value3".to_string());
    cache.put("key4".to_string(), "value4".to_string()); // 这会移除最旧的 "key1"
    
    println!("   LRU缓存中 key1 的值: {:?}", cache.get(&"key1".to_string()));
    println!("   LRU缓存中 key2 的值: {:?}", cache.get(&"key2".to_string()));
    println!("   LRU缓存中 key4 的值: {:?}", cache.get(&"key4".to_string()));
    
    // 演示二叉树
    let mut root = TreeNode::new(10);
    root.add_left(5);
    root.add_right(15);
    println!("   二叉树根节点: {:?}", root.value);
    println!("   左子节点: {:?}", root.left.as_ref().map(|n| n.value));
    println!("   右子节点: {:?}", root.right.as_ref().map(|n| n.value));
    
    println!();
}

fn demonstrate_concurrent_utils() {
    println!("=== 并发工具演示 ===");
    
    // 演示并行计算
    let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    let sum = parallel_sum(&data);
    println!("   并行计算数组和: {}", sum);
    
    // 演示并行映射
    let doubled: Vec<i32> = parallel_map(&data, |x| x * 2);
    println!("   并行映射结果: {:?}", doubled);
    
    // 演示并行过滤
    let evens: Vec<i32> = parallel_filter(&data, |&x| x % 2 == 0);
    println!("   并行过滤偶数: {:?}", evens);
    
    // 演示线程池
    let pool = ThreadPool::new(4).expect("Failed to create thread pool");
    let counter = std::sync::Arc::new(std::sync::Mutex::new(0));
    
    for i in 0..10 {
        let counter_clone = std::sync::Arc::clone(&counter);
        pool.execute(move || {
            let mut num = counter_clone.lock().unwrap();
            *num += 1;
            println!("   任务 {} 完成，当前计数: {}", i, *num);
        });
    }
    
    // 等待所有任务完成
    thread::sleep(Duration::from_millis(100));
    println!("   最终计数: {}", *counter.lock().unwrap());
    
    // 演示通道超时操作
    let (s, r) = crossbeam::channel::unbounded();
    match send_with_timeout(s, "Hello", Duration::from_millis(100)) {
        Ok(_) => println!("   通道发送成功"),
        Err(e) => println!("   通道发送失败: {:?}", e),
    }
    
    match recv_with_timeout(r, Duration::from_millis(100)) {
        Ok(msg) => println!("   通道接收消息: {}", msg),
        Err(e) => println!("   通道接收失败: {:?}", e),
    }
    
    println!();
}

fn demonstrate_serialization() {
    println!("=== 序列化工具演示 ===");
    
    let person = Person {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
        age: 30,
    };
    
    // JSON序列化
    match JsonSerializer::to_string(&person) {
        Ok(json_str) => {
            println!("   JSON序列化结果: {}", json_str);
            
            match JsonSerializer::from_string::<Person>(&json_str) {
                Ok(deserialized) => {
                    println!("   JSON反序列化结果: {:?}", deserialized);
                    println!("   序列化/反序列化一致性: {}", person == deserialized);
                },
                Err(e) => println!("   JSON反序列化失败: {}", e),
            }
        },
        Err(e) => println!("   JSON序列化失败: {}", e),
    }
    
    // XML序列化
    match XmlSerializer::to_string(&person, "person") {
        Ok(xml_str) => println!("   XML序列化结果长度: {} 字符", xml_str.len()),
        Err(e) => println!("   XML序列化失败: {}", e),
    }
    
    // Extended demo中的User序列化
    let user = User {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
        age: 30,
    };
    
    // JSON序列化
    let json_str = JsonSerializer::to_string(&user).unwrap();
    println!("   User JSON序列化结果: {}", json_str);
    
    let deserialized_user: User = JsonSerializer::from_string(&json_str).unwrap();
    println!("   User JSON反序列化结果: {:?}", deserialized_user);
    
    // XML序列化
    let xml_str = XmlSerializer::to_string(&user, "user").unwrap();
    println!("   User XML序列化结果: {}", xml_str);
    
    println!();
}

fn demonstrate_validation() {
    println!("=== 验证工具演示 ===");
    
    // 电子邮件验证
    let email_validator = EmailValidator;
    let valid_email = "user@example.com".to_string();
    let invalid_email = "invalid-email".to_string();
    
    println!("   验证邮箱 '{}': {:?}", valid_email, email_validator.validate(&valid_email));
    println!("   验证邮箱 '{}': {:?}", invalid_email, email_validator.validate(&invalid_email));
    
    // 手机号验证
    let phone_validator = PhoneNumberValidator;
    let valid_phone = "13812345678".to_string();
    let invalid_phone = "12345".to_string();
    
    println!("   验证手机号 '{}': {:?}", valid_phone, phone_validator.validate(&valid_phone));
    println!("   验证手机号 '{}': {:?}", invalid_phone, phone_validator.validate(&invalid_phone));
    
    // 长度验证
    let length_validator = LengthValidator::new().min(3).max(10);
    let valid_string = "hello".to_string();
    let short_string = "hi".to_string();
    let long_string = "this is a very long string".to_string();
    
    println!("   验证字符串 '{}': {:?}", valid_string, length_validator.validate(&valid_string));
    println!("   验证字符串 '{}': {:?}", short_string, length_validator.validate(&short_string));
    println!("   验证字符串 '{}': {:?}", long_string, length_validator.validate(&long_string));
    
    // 范围验证
    let range_validator = RangeValidator::new().min(1).max(100);
    let valid_number = 50;
    let small_number = 0;
    let large_number = 150;
    
    println!("   验证数字 {}: {:?}", valid_number, range_validator.validate(&valid_number));
    println!("   验证数字 {}: {:?}", small_number, range_validator.validate(&small_number));
    println!("   验证数字 {}: {:?}", large_number, range_validator.validate(&large_number));
    
    // 组合验证
    let mut composite_validator = CompositeValidator::new();
    composite_validator.add_validator(Box::new(EmailValidator));
    composite_validator.add_validator(Box::new(LengthValidator::new().min(5)));
    
    let valid_email = "user@example.com".to_string();
    let invalid_email = "us@x.c".to_string();
    
    println!("   组合验证邮箱 '{}': {:?}", valid_email, composite_validator.validate(&valid_email));
    println!("   组合验证邮箱 '{}': {:?}", invalid_email, composite_validator.validate(&invalid_email));
    
    println!();
}

fn demonstrate_logging() {
    println!("=== 日志工具演示 ===");
    
    // 初始化日志系统
    match init_logger(log::LevelFilter::Debug, None) {
        Ok(_) => println!("   日志系统初始化成功"),
        Err(e) => println!("   日志系统初始化失败: {:?}", e),
    }
    
    // 基本日志
    log::info!("这是一条信息日志");
    log::debug!("这是一条调试日志");
    log::warn!("这是一条警告日志");
    log::error!("这是一条错误日志");
    
    // 结构化日志
    StructuredLogger::log_info("user_action", "用户登录", Some("用户ID: 12345"));
    StructuredLogger::log_warning("config_warning", "配置项缺失", Some("使用默认值"));
    StructuredLogger::log_error("database_connection", "连接数据库失败", Some("连接超时"));
    
    // 函数装饰器
    log_function("demo_function", || {
        println!("   在demo_function内部执行");
        thread::sleep(Duration::from_millis(10));
    });
    
    // 性能计时
    time_function("slow_operation", || {
        println!("   执行耗时操作");
        thread::sleep(Duration::from_millis(50));
    });
    
    println!();
}

fn demonstrate_id_card() {
    println!("=== 身份证验证工具演示 ===");
    
    let validator = IdCardValidator;
    
    // 验证18位身份证
    let valid_18_id = "11010519491231002X";
    let result = validator.validate_18(valid_18_id);
    println!("   验证18位身份证 '{}': {:?}", valid_18_id, result);
    
    // 验证15位身份证
    let valid_15_id = "110105491231002";
    let result = validator.validate_15(valid_15_id);
    println!("   验证15位身份证 '{}': {:?}", valid_15_id, result);
    
    // 验证错误的身份证
    let invalid_id = "110105194912310021"; // 校验码错误
    let result = validator.validate(invalid_id);
    println!("   验证错误身份证 '{}': {:?}", invalid_id, result);
    
    // 解析身份证信息
    match validator.parse(valid_18_id) {
        Ok(info) => {
            println!("   身份证信息解析结果:");
            println!("     身份证号码: {}", info.id_card);
            println!("     出生日期: {}", info.birth_date);
            println!("     性别: {}", if info.gender == 1 { "男" } else { "女" });
            println!("     地区码: {}", info.area_code);
            println!("     地区名称: {}", info.area_name);
        },
        Err(e) => println!("   身份证解析失败: {}", e),
    }
    
    println!();
}

fn main() {
    println!("Rust 常用工具库完整功能演示\n");
    
    demonstrate_string_utils();
    demonstrate_math_utils();
    demonstrate_file_utils();
    demonstrate_time_utils();
    demonstrate_collection_utils();
    demonstrate_crypto_utils();
    demonstrate_network_utils();
    demonstrate_system_utils();
    demonstrate_data_structures();
    demonstrate_concurrent_utils();
    demonstrate_serialization();
    demonstrate_validation();
    demonstrate_logging();
    demonstrate_id_card(); // 添加身份证验证演示
    
    println!("所有模块演示完成！");
}